<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    title="重置密码"
    width="800px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { resetPassword } from '@/api/user'
  import { ResetPasswordParams } from '@/api/model/user';

  const emit = defineEmits(['success', 'register']);
  const id = ref();

  const schemas: FormSchema[] = [
    {
      field: 'name',
      label: '姓名',
      component: 'Input',
      required: true,
      dynamicDisabled: true,
    },
    {
      field: 'username',
      label: '账号',
      component: 'Input',
      required: true,
      dynamicDisabled: true,
    },
    {
      field: 'new_password',
      label: '新密码',
      component: 'InputPassword',
      required: true,
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: schemas,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    id.value = data?.record?.id;
    resetFields();
    setDrawerProps({ confirmLoading: false });
    setFieldsValue({
      ...data.record,
    });
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: ResetPasswordParams = {
        user_id: id.value,
        new_password: values.new_password,
      }
      await resetPassword(params);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>